package com.shadow.demo.shiro.shiro.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 安全认证过滤器.
 * @version v1.0
 * @ClassName: SecurityFilter
 * @author: Pbody
 * @Date: 2020/8/5 9:57
 */
public class SecurityFilter extends FormAuthenticationFilter {

    /**
     * 执行登录认证.
     * @param request 请求对象
     * @param response 响应对象
     * @param mappedValue 对象值
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(final ServletRequest request, final ServletResponse response, final Object mappedValue) {
        if (null == SecurityUtils.getSubject().getPrincipal()) {
            return ssoFromOaLogin(request);
        }
        return true;
    }

    /**
     * OA单点.
     * @duthor Pbody
     * @date 18:38 2020/8/11
     * @param request 请求对象
     * @return void
     **/
    private static boolean ssoFromOaLogin(final ServletRequest request) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final String userId = httpRequest.getRemoteUser();
        // 获取sso账号
        if (StringUtils.isNotBlank(userId)) {
            final Subject subject = SecurityUtils.getSubject();
            final UsernamePasswordToken token = new UsernamePasswordToken(userId, "");
            subject.login(token);
            return true;
        }
        return false;
    }
}
